<script setup lang='ts'>
  import { onMounted, onUpdated, reactive, ref } from 'vue';
  import { luckDrawApi } from '@/api/controller';
  import { ToastSuccess, Toastloading, $router } from '@/utils/public';
  import { ElMessageBox } from 'element-plus';
  import addForm from './addForm.vue';
  const addFormRef = ref()
  const action = reactive({
    list:[] as any[],
    pool_level:0
  })
  const handleDel = (row:any = {})=>{
    const { gift_name, id } = row
    ElMessageBox.confirm(`确定删除礼物：${gift_name}吗?`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
    .then(async () => {
      const loading = Toastloading()
      await luckDrawApi.wishDefenderDelGift({
        id
      })
      ToastSuccess('删除成功')
      getList()
      loading.close()
    })
    .catch(() => {});
  }
  const handleForm = ()=>{
    addFormRef.value.openDialog({
      pool_level:action.pool_level
    })
  }
  const getList = async()=> {
    const loading = Toastloading()
    const res = await luckDrawApi.wishDefenderGiftList({
      pool_level:action.pool_level
    })
    loading.close()
    const { data=[] } = res
    action.list = data
  }
  let primarySet = false
  const getPoolLevel = async()=>{
    if(primarySet) return
    primarySet = true
    const { pool_level=0 } = $router().currentRoute.value?.meta || { pool_level:0 }
    if(action.pool_level != pool_level && pool_level) {
      action.pool_level = pool_level as number
      const loading = Toastloading()
      action.list = []
      await getList()
      primarySet = false
      loading.close()
    }
  }
  const updatePoolLevel = ()=>{
    primarySet = false
    getPoolLevel()
  }
  onMounted(()=>{
    updatePoolLevel()
  })
  onUpdated(()=>{
    updatePoolLevel()
  })
</script>

<template>
  <div class="xm-content">
    <div class="xm-headTab">
      <div class="labelBox">
        <div class="labelItem">
          <el-button type="primary" @click="handleForm()">新增</el-button>
        </div>
      </div>
    </div>
    <el-table
      class="xm-main xm-TableCenter"
      :data="action.list"
      border
    >
      <el-table-column min-width="100" prop="sort" label="排序" />
      <el-table-column min-width="120" prop="gift_id" label="礼物ID" />
      <el-table-column min-width="120" prop="gift_name" label="礼物名称" />
      <el-table-column min-width="120" prop="gift_price" label="礼物价格" />
      <el-table-column label="操作" fixed="right" width="260">
        <template #default="scoped">
          <el-button type="danger" @click="handleDel(scoped.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <addForm ref="addFormRef" @update-list="getList" />
  </div>
</template>
